<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Admin_Chapter extends Controller_Admin_Template
{
   
    
    public function action_index()
    {
        $chapters = View::factory('admin/chapter/chapter')
                        ->set('chapters', $this->get_chapters());
        $this->template->content = $chapters->render();        
    }
    
    public function get_chapters($parent_id = 0)
    {
        $chapters = array();
        $result = DB::query(Database::SELECT, "SELECT c1.id as `id`, c1.name as `name`, c1.href as `href`, c1.hide as `hide`, c1.parent_id as `parent_id`, (COUNT( c2.name )>0) as `subchapters` 
                                                FROM  `chapters` AS  `c1` 
                                                LEFT JOIN  `chapters` AS  `c2` ON c2.parent_id = c1.id
                                                WHERE c1.parent_id =$parent_id                                                
                                                GROUP BY c1.name
                                                ORDER BY c1.pos")
                    ->execute();        
        foreach ($result as $chapter) {
            if($chapter['subchapters'])
                $chapter['subchapters'] = $this->get_chapters($chapter['id']);
            else
                unset($chapter['subchapters']);
            $chapters[] = $chapter;
        }
        return $chapters;
    }
    
    public function action_add()
    {
        $this->auto_render = false;
        $response = array();
        
        if(Request::$initial->is_ajax()){            
            $chapter = ORM::factory('chapter')
                            ->values($_POST);
            try
            {
                $chapter->save();                
                $chapter->pos = DB::query(Database::SELECT, "SELECT MAX(pos) + 1 as `pos`
                                                             FROM `chapters`
                                                             WHERE `parent_id`={$chapter->parent_id}")
                                    ->execute()
                                    ->get('pos');                          

                $chapter->save();
                $response = array('status' => 'ok');
            }
            catch(ORM_Validation_Exception $e)
            {
                $errors = $e->errors('admin');
                $response = array('status' => 'error',
                                  'error' => $errors);
            }
        } else 
            $response = array('status' => 'error');
        
        $this->response->body(json_encode($response));
    }
    
    public function action_hide()
    {
        $id = Arr::get($_REQUEST, 'id', -1);
        if($id != -1){
            $hide = ORM::factory('chapter', $id)->__get('hide');
            if($hide == 'hide')
                $this->show($id);
            else
                $this->hide($id);
        }
        
        Request::$initial->redirect('admin/chapter');
    }
    
    public function hide($id)
    {
        ORM::factory('chapter', $id)->set('hide','hide')->save();
           
        $chapters = ORM::factory('chapter')->where('parent_id', '=', $id)->find_all();
        foreach ($chapters as $chapter){
            $this->hide($chapter->id);
        }    
    }
    
    public function show($id)
    {
        if($id != 0){
            $chapter = ORM::factory('chapter', $id);
            $chapter->hide = 'show';
            $chapter->save();
            
            $this->show($chapter->parent_id);
        }
    }
    
    public function action_save()
    {
        $this->auto_render = false;
        
        $id = Arr::get($_POST, 'id', 0);
        $response = array();
        
        $chapter = ORM::factory('chapter', $id);
        if($chapter->loaded()){
            $chapter->values($_POST);
            try
            {
                $chapter->save();
                $response = array('status' => 'ok');
            }
            catch(ORM_Validation_Exception $e)
            {
                $errors = $e->errors('admin');
                $response = array('status' => 'error',
                                  'error' => $errors);
            }
        } else {
            $response = array('status' => 'error');
        }
        
        $this->response->body(json_encode($response));
 
    }
    
    public function action_delete()
    {
        $this->delete(Arr::get($_REQUEST, 'id', 0));
        
        Request::$initial->redirect('admin/chapter');
    }
    
    public function delete($id)
    {
        if($id != 0)
        {
            $chapters = DB::query(Database::SELECT, "SELECT `id` FROM `chapters` 
                                                     WHERE `parent_id`=:parent_id")
                           ->param(':parent_id', $id)
                           ->as_object()
                           ->execute();
            foreach ($chapters as $chapter) {
                $this->delete($chapter->id);
            }
            ORM::factory('chapter', $id)->delete();            
        }
    }
    
    public function action_up()
    {
        $id = Arr::get($_REQUEST, 'id', 0);
        if($id != 0) {
            $chapter = ORM::factory('chapter', $id);
            
            $query = DB::query(Database::SELECT, "SELECT `id`, `pos`
                                                  FROM `chapters`
                                                  WHERE (`pos` < {$chapter->pos} AND `parent_id`={$chapter->parent_id})
                                                  ORDER BY `pos` DESC
                                                  LIMIT 1");
            
            $result = $query->execute();
            if($result->count() > 0){
                $up_id = $result->get('id');
                $up_pos = $result->get('pos');
                
                $up_chapter = ORM::factory('chapter', $up_id);
                $up_chapter->pos = $chapter->pos;
                $up_chapter->save();
                
                $chapter->pos = $up_pos;
                $chapter->save();
            }
        }
        
        Request::$initial->redirect('admin/chapter');
    }
    
    public function action_down()
    {
        $id = Arr::get($_REQUEST, 'id', 0);
        if($id != 0) {
            $chapter = ORM::factory('chapter', $id);
            
            $query = DB::query(Database::SELECT, "SELECT `id`, `pos`
                                                  FROM `chapters`
                                                  WHERE (`pos` > {$chapter->pos} AND `parent_id`={$chapter->parent_id})
                                                  ORDER BY `pos` ASC
                                                  LIMIT 1");
            
            $result = $query->execute();
            if($result->count() > 0){
                $down_id = $result->get('id');
                $down_pos = $result->get('pos');
                
                $down_chapter = ORM::factory('chapter', $down_id);
                $down_chapter->pos = $chapter->pos;
                $down_chapter->save();
                
                $chapter->pos = $down_pos;
                $chapter->save();
            }
        }
        
        Request::$initial->redirect('admin/chapter');
    }
    
    public function action_get()
    {
        $this->auto_render = false;
        $response = array();
        if(Request::$initial->is_ajax()){
            $id = Arr::get($_POST, 'id', 0);
            $chapter = ORM::factory('chapter', $id);
            if($chapter->loaded()){
                $response = array('status' => 'ok',
                                  'name' => $chapter->name,
                                  'href' => $chapter->href);
            } else {
                $response = array('status' => 'error');
            }
        }
        
        $this->response->body(json_encode($response));
    }
}